import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:jinke/utils/fun_util.dart';
import 'package:jinke/utils/web_channel.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';

import '../../../utils/httputils/api.dart';
import '../../../utils/httputils/httpmanager.dart';
import '../../../utils/httputils/resultdata.dart';
import '../../../utils/httputils/urlpath.dart';
import '../../../utils/util.dart';
import '../model/ReportDetailEntity.dart';
import '../model/ReportEntity.dart';
import 'state.dart';
// import 'dart:js' as js;

class ReportDetailLogic extends GetxController {
  final ReportDetailState state = ReportDetailState();
  @override
  void onInit() {
    super.onInit();

    state.entity = Get.arguments;
    getReportStatistics();
    getReportDetail();

    saveDyaReportRead();
  }

  saveDyaReportRead() async {
    var params = {
      'reportDate': state.entity.reportDate,
      'specialType': state.entity.specialType
    };

    ResultData response = await Api.saveDyaReportRead(params);

    if (response.isSuccess) {}
  }

  getReportDetail() async {
    var params = {
      'entity': {
        'reportDate': state.entity.reportDate,
        'specialType': state.entity.specialType
      }
    };

    ResultData response = await Api.getReportDetail(params);

    if (response.isSuccess) {
      List _data = response.data;
      state.detailentityList =
          _data.map((e) => ReportDetailEntity.fromJson(e)).toList();
      update();
    }
  }

  batchSave() async {
    var params = [];
    state.detailentityList.forEach((element) {
      var param = {
        'content': element.editReportEvolveContent,
        'endTime': element.reportDate,
        'id': element.id,
        'isValid': 1,
        'projectId': element.projectId,
        'reportState': 1,
        'reportState': 2,
        'startTime': element.reportDate,
      };
      params.add(param);
    });

    ResultData response = await Api.batchSave(params);

    if (response.isSuccess) {
      BrnDialogManager.showSingleButtonDialog(Get.context!,
          showIcon: true, title: "保存成功", label: "确定", onTap: () {
        Get.back();
        Get.back(result: true);
      });
    }
  }

  getReportStatistics() async {
    var params = {
      'reportDate': state.entity.reportDate,
      'specialType': state.entity.specialType
    };

    ResultData response = await Api.getReportStatistics(params);

    if (response.isSuccess) {
      state.totleInsert = response.data['totleInsert'];
      state.newInsert = response.data['newInsert'];
      state.statusZb = response.data['statusZb'];
    }
  }

  getDownLoadUrl(bool isShare) async {
    ResultData response =
        await Api.saProjectReportShare(state.entity.reportDate ?? '');
    String idAddr = response.data['idAddr'].toString();
    String fileVisitUrl = response.data['fileVisitUrl'].toString();
    String fileName = response.data['fileName'].toString();

    if (isWeb) {
      // js.context["app"].callMethod(isShare ? 'share' : "downloadFile",
      //     [idAddr + fileVisitUrl, fileName]);
      // js.context[isShare ? 'share' : "downloadFile"]
      //     .callMethod('postMessage', [idAddr + fileVisitUrl, fileName]);
      // showToast('toast_channel');
      // showToast(jsonEncode({
      //   'url': idAddr + fileVisitUrl,
      //   'name': fileName,
      //   'type': 1,
      // }));
    } else {
      downFile(
          response.data['idAddr'].toString() +
              response.data['fileVisitUrl'].toString(),
          response.data['fileName'],
          isShare: isShare);
    }
  }

  downFile(String url, String name, {bool isShare = false}) async {
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;
    await HttpManager.downloadFile(url, appDocPath + name,
        downloadProgressCallBack: (int count, int total) {
      print('-----$count/$total');
    });

    if (!isShare) {
      Get.showSnackbar(
        GetSnackBar(
          title: '下载完成',
          message: appDocPath + name,
          duration: const Duration(seconds: 5),
        ),
      );
    } else {
      shareFile(appDocPath + name);
    }
  }

  shareFile(String path) {
    Share.shareFiles([path]);
  }
}
